import 'dart:convert';

import 'package:chewie/chewie.dart';
import 'package:effective/model/result_entity.dart';
import 'package:effective/model/speech_entity.dart';
import 'package:effective/service/api.dart';
import 'package:effective/utils/base_model.dart';
import 'package:effective/view_model/user_model.dart';
import 'package:effective/widget/common_dialog.dart';
import 'package:effective/widget/cos.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:video_player/video_player.dart';
import 'package:sprintf/sprintf.dart';

class AnnotationViewModel extends BaseModel {
  bool isAgain;
  bool agreeNotice = false;
  bool agreeVolunteer = false;

  ChewieController chewieController;
  VideoPlayerController controller;

  TextEditingController description = TextEditingController();

  //false 代表start end相反
  bool startOrEnd = false;
  String startTime;
  SpeechVideoEntity _speechVideoEntity;

  void changeNoticeState(bool value) {
    agreeNotice = value;
    notifyListeners();
  }

  void changeVolunteer(bool value) {
    agreeVolunteer = value;
    notifyListeners();
  }

  List<Highlight> highlights = [];

  AnnotationViewModel({API api}) : super(api: api);

  Future<void> logout(BuildContext context) async {
    showDialog(
        context: (context),
        builder: (context) {
          return AlertDialog(
            content: Container(
              child: Text('确认要退出登录吗？'),
            ),
            actions: [
              TextButton(
                  onPressed: () {
                    context.read<UserModel>().update("");
                    Navigator.pop(context);
                  },
                  child: Text('确认')),
              TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: Text('取消')),
            ],
          );
        });
  }

  Future<void> login(BuildContext context) async {
    /*Cos cos = new Cos(
        "AKIDf6qJ1TD7QUGXpsLtsa3FnaiaAe6IoZdQ",
        "g6V2h7PSKwHsTaRu97pF60XoQovnRtzR",
        "https://markdown-1305004560.cos.ap-beijing.myqcloud.com");
    String url = await cos.upload("/", fileByte);
    print(url);*/
    ResultEntity resultEntity = await CommonDialog().loginDialog(context);
    if (resultEntity != null) {
      context.read<UserModel>().update(resultEntity.data['username']);
      context.read<UserModel>().token = resultEntity.data['token'];
      notifyListeners();
      loadData(context);
    }

  }

  Future loadData(BuildContext context) async {
    setState(ViewState.Busy);
    _speechVideoEntity = SpeechVideoEntity();
    //数据加载
    if (Provider.of<UserModel>(context).token == '') {
      _speechVideoEntity = SpeechVideoEntity();
      controller =
          VideoPlayerController.network("http://" + _speechVideoEntity.video)
            ..initialize().then((_) {
              print('初始化结束');
              chewieController = ChewieController(
                videoPlayerController: controller,
                autoPlay: false,
                placeholder: Container(
                  color: Colors.grey,
                ),
              );
              notifyListeners();
            });
    } else {
      ResultEntity resultEntity =
          await api.getSpeech(context.read<UserModel>().token);
      if (resultEntity.code == 200) {
        //加载数据
        _speechVideoEntity = SpeechVideoEntity().fromJson(resultEntity.data);
        description.text = _speechVideoEntity.description;
        highlights = _speechVideoEntity.highlights.map((e) {
          String res = e;
          res = res.replaceFirst("id", "\"id\"");
          res= res.replaceFirst("start", "\"start\"");
          res= res.replaceFirst("end", "\"end\"");
          res= res.replaceAll("\":", "\":\"");
          res= res.replaceAll(",", "\",");
          res = res.replaceAll("}", "\"}");
          print(res);
          return Highlight.fromJson(JsonDecoder().convert(res));
        }).toList();
        controller =
            VideoPlayerController.network("http://" + _speechVideoEntity.video)
              ..initialize().then((_) {
                print('初始化结束');
                chewieController = ChewieController(
                  videoPlayerController: controller,
                  autoPlay: false,
                  fullScreenByDefault: false,
                  allowFullScreen: false,
                  placeholder: Container(
                    color: Colors.grey,
                  ),
                );
                notifyListeners();
              });
      } else {
        _speechVideoEntity = SpeechVideoEntity();
      }
    }
    setState(ViewState.Idle);
  }

  void hightlightStart(int time) {
    int hour = time ~/ 1000 ~/ 60 ~/ 60;
    int minute = (time - hour * 60 * 60 * 1000) ~/ 60 ~/ 1000;
    int second = (time - hour * 60 * 60 * 1000 - minute * 60 * 1000) ~/ 1000;
    int left =
        (time - hour * 60 * 60 * 1000 - minute * 60 * 1000 - second * 1000) ~/
            10;
    startTime = sprintf("%02d:%02d:%02d:%02d", [hour, minute, second, left]);
    startOrEnd = !startOrEnd;
    notifyListeners();
  }

  void hightlightEnd(int time) {
    Highlight highlight = new Highlight();
    highlight.start = startTime;
    int hour = time ~/ 1000 ~/ 60 ~/ 60;
    int minute = (time - hour * 60 * 60 * 1000) ~/ 60 ~/ 1000;
    int second = (time - hour * 60 * 60 * 1000 - minute * 60 * 1000) ~/ 1000;
    int left =
        (time - hour * 60 * 60 * 1000 - minute * 60 * 1000 - second * 1000) ~/
            10;
    String endTime =
        sprintf("%02d:%02d:%02d:%02d", [hour, minute, second, left]);
    highlight.end = endTime;
    highlights.add(highlight);
    startOrEnd = !startOrEnd;
    notifyListeners();
  }

  void deleteHighlight(int pos) {
    highlights.removeAt(pos);
    notifyListeners();
  }

  Future submit(BuildContext context) async {
    if (!(agreeNotice && agreeVolunteer)) {
      showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: Text('提示'),
              content: Text('您还未勾选同意说明'),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                    return;
                  },
                  child: Text('确定'),
                ),
              ],
            );
          });
    }

    _speechVideoEntity.description = description.text.trim();
    _speechVideoEntity.highlights =
        highlights.map((e) => e.toString()).toList();
    Fluttertoast.showToast(msg: "正在提交");
    ResultEntity resultEntity = await api.updateSpeech(
        context.read<UserModel>().token, _speechVideoEntity);
    if (resultEntity.code == 200) {
      Fluttertoast.showToast(msg: "提交成功");
    } else {
      Fluttertoast.showToast(msg: resultEntity.message);
    }
  }

  void reset() {
    description.text = '';
    highlights = [];
  }
}

class Highlight {
  String id;
  String start;
  String end;

  @override
  String toString() {
    return '{\"id\": \"$id\", \"start\": \"$start\", \"end\": \"$end\"}';
  }

  Highlight() {}

  Highlight.fromJson(Map<dynamic, dynamic> json) {
    this.id = json['id'];
    this.start = json['start'];
    this.end = json['end'];
  }
}
